import axios from 'axios'
import { Loading } from 'element-ui';

//获取axios实例
let instance = axios.create({
    baseURL: 'http://localhost:8080/admin'
})

//加载模块的实例对象
let loadingInstance

//请求拦截
instance.interceptors.request.use(config=>{
    // 请求前的处理
    loadingInstance = Loading.service({
        target: '.el-table',
        text: '稍等片刻'
    });

    //在请求头中设置token
    config.headers = {
        token: localStorage.token
    }

    return config
},err=>{
    // 请求错误处理

    return Promise.reject(err);
})

//响应拦截
instance.interceptors.response.use(res=>{
    //处理响应拦截
    loadingInstance.close()
    return res

},err => {
    // 请求错误处理
    loadingInstance.close()
    return Promise.reject(err);
})

//通用的请求方法
const http = async ({path, method = 'get', params}) => {
    let result

    if(method === 'get' || method === 'delete'){
        await instance[method](path, {
            params
        }).then(res=>{
            result = res.data
        }).catch(err => {
            result = err
        })
    }else if(method === 'post' || method === 'put' || method === 'patch'){
        await instance[method](path, params).then(res=>{
            result = res.data
        }).catch(err => {
            result = err
        })
    }
    
    return result
}

export default http

